﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Core.Models;
using System.Web.Security;
using System.Security.Principal;
using System.Web.Hosting;
using Core.Plugin;
using System.Configuration;

namespace Core
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "htm",
                "{*Url}",
                new { controller = "Url", action = "Process" },
                new { Url = new InStrings(new string[] {"htm","html","aspx"}) }
            );

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
                new string[] { "Core.Controllers" }
            );
        }

        protected void Application_Start()
        {
            Application["DebugInfo"] = ConfigurationManager.AppSettings["Debug"].ToString() == "true" ? true : false;
            Application["DebugSequence"] = (int)0;
            System.Web.Mvc.ModelMetadataProviders.Current = new DataAnnotationsModelMetadataProvider();
            HostingEnvironment.RegisterVirtualPathProvider(new AssemblyResourceProvider());
            PluginHelper.InitializePluginsAndLoadViewLocations();
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }


        protected void Session_Start()
        {
            try
            {
                CoreEntities core = new CoreEntities();
                if (Request.IsAuthenticated)
                {
                    Guid UserId = new Guid(Context.User.Identity.Name);
                    Session["UserId"] = UserId;
                    Core.Models.User user = core.Users.First(m => m.UserId == UserId);
                    Session["UserFullName"] = user.Contact.FullName;
                    Session["UserEmail"] = user.Contact.Email;
                }
                else
                {
                    Session["UserId"] = Guid.Empty;
                    Session["UserFullName"] = "";
                    Session["UserEmail"] = "";
                }
                Session["IsSmallDevice"] = false;
                Session["URL"] = "";
                Session["RegisterModel"] = new Core.Models.RegisterModel();
                Session["UserCompanyId"] = Guid.Empty;
                string domainName = Request.ServerVariables["HTTP_HOST"].ToString();
                Core.Tools.DebugInfo("Session Domain name = " + domainName);
                Session["DomainName"] = domainName;
                Domain domain = core.Domains.First(d => d.DomainName == domainName);
                Session["DomainId"] = domain.DomainId;
                Session["SiteTitle"] = domain.SiteTitle;
                Session["GoogleAnalyticsAccount"] = domain.GoogleAnalyticsAccount;
                Core.Tools.DebugInfo("Session Start: Setting Theme");
                Core.Tools.DebugInfo("Session Start: Browser detected = " + Request.UserAgent);
                Core.Tools.DebugInfo("Session Start: Browser Platform = " + Request.Browser.Platform);
                Theme theme;
                theme = core.Themes.First(t => t.ThemeId == domain.ThemeId);
                if (Request.Browser.IsMobileDevice && (domain.MobileThemeId.HasValue))
                {
                    Session["IsSmallDevice"] = true;
                    theme = core.Themes.First(t => t.ThemeId == domain.MobileThemeId);
                }
                Session["Theme"] = theme;
                Core.Tools.DebugInfo("Session Start: Theme set to " + theme.Name);
                Session["EnableSelfRegisterYN"] = domain.EnableSelfRegisterYN;
                Session["ReCaptchaPublicKey"] = domain.ReCaptchaPublicKey;
                Session["ReCaptchaPrivateKey"] = domain.ReCaptchaPrivateKey;
                if (domain.IsMultiBUYN == "N")
                {                    
                    BusinessUnit bu = core.BusinessUnits.First(b => b.DomainId == domain.DomainId);
                    Session["BusinessUnitId"] = bu.BusinessUnitId;
                    Session["BusinessUnitName"] = bu.BusinessUnitName;
                }
                else
                {
                    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                    if (authCookie != null)
                    {
                        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                        List<string> budata = authTicket.UserData.Split(("|").ToCharArray(), 9999).ToList();
                        Session["BusinessUnitId"] = new Guid(budata[0]);
                        Session["BusinessUnitName"] = budata[1];
                    }
                    else
                    {
                        BusinessUnit bu = core.BusinessUnits.First(b => b.BusinessUnitId == domain.PrimaryBU);
                        Session["BusinessUnitId"] = bu.BusinessUnitId;
                        Session["BusinessUnitName"] = bu.BusinessUnitName;
                    }
                }
                Session["IsValid"] = true;
            }
            catch(Exception e) 
            {
                Core.Tools.DebugInfo("Session Start: Error " + Tools.ExceptionMessage(e));
                Theme theme = new Theme();
                theme.Layout = "~/Views/Shared/_Layout.cshtml";
                Session["Theme"] = theme;
                Session["IsValid"] = false;
            }
        }
    }
}